package com.swotxu.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.swotxu.common.constant.AuthServerConstant;
import com.swotxu.common.constant.MallUrlConstant;
import com.swotxu.common.utils.HttpUtils;
import com.swotxu.common.utils.R;
import com.swotxu.common.vo.MemberRespVo;
import com.swotxu.mall.auth.feign.MemberFeignService;
import com.swotxu.mall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * 处理社交登陆请求
 *
 * @Date: 2021/2/28 16:05
 * @Author: swotXu
 */
@Slf4j
@Controller
@RequestMapping("/oauth2.0")
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 根据微博回调时提供的code码，换取 Access Token
     * @param code
     * @return
     */
    @GetMapping("/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        HashMap<String, String> map = Maps.newHashMap();
        map.put("client_id", "369168801");
        map.put("client_secret", "1810a810f3d42f383b6c529b61692c6b");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", MallUrlConstant.AUTH_WEIBO_SUCCESS);
        map.put("code", code);
        // 换取 Access Token
        HttpResponse httpResponse = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", HttpUtils.HTTP_POST, null, null, map);

        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            // 失败，重定向到登陆页
            return MallUrlConstant.AUTH_REDIRECT_LOGIN;
        }
        String bodyJsonStr = EntityUtils.toString(httpResponse.getEntity());
        SocialUser socialUser = JSON.parseObject(bodyJsonStr, SocialUser.class);
        // 自动注册，生成会员信息账号
        R loginRes = memberFeignService.oauthLogin(socialUser);
        if (!loginRes.isOk()) {
            log.warn("登录失败！{}", loginRes.getMessage());
            // 失败，重定向到登陆页
            return MallUrlConstant.AUTH_REDIRECT_LOGIN;
        }
        MemberRespVo respVo = loginRes.getData(MemberRespVo.class);
        log.info("登录成功！{}", respVo);
        // TODO 解决不同域共享问题，以及使用JSON序列化方式
        session.setAttribute(AuthServerConstant.SESSION_LOGIN_USER, respVo);

        return MallUrlConstant.REDIRECT_MALL_MAIN_INDEX;
    }
}
